package sequenceimport ()const (SequenceDiagramKeyword = "sequenceDiagram"SolidArrowSyntax = "->>"DottedArrowSyntax = "-->>")var (// participantRegex matches participant declarations: participant [rest] or // actor [rest]. mermaid renders an actor as a stick figure; in ASCII both // forms draw the same labelled box. The rest ([ID] [as Label]) is split by // parseParticipant, because IDs may contain spaces (mermaid's ID lexer // state allows them: "participant cron job as Cron"). participantRegex = regexp.MustCompile(`(?i)^\s*(?:participant|actor)\s+(.+)$`)// participantAsRegex splits "ID as Label" at the FIRST " as ", matching // mermaid's lexer for whitespace-free IDs. For IDs containing spaces this // is a deliberate extension: mermaid's alias rule only fires for // whitespace-free IDs, so it would read the whole line as one long name. participantAsRegex = regexp.MustCompile(`(?i)^(.*?\S)\s+as\s+(.+)$`)// fragmentKeywordRegex guards message parsing: mermaid lexes fragment // keywords before actor names, so a line whose first word is one of them // is never a message — even when its label contains an arrow and a colon // ("else fall back -> retry: yes"). fragmentKeywordRegex = regexp.MustCompile(`(?i)^(loop|opt|alt|par|critical|break|rect|else|and|option|end)\b`)// arrowTokens are mermaid's ten message arrows, longest first so that at // any position the longest token wins (e.g. "-->>" is never read as // "-->", "--)" never as "--" + ")"). arrowTokens = []string{"<<-->>", "<<->>", "-->>", "--x", "--)", "-->", "->>", "-x", "-)", "->"}// autonumberRegex matches the autonumber directive autonumberRegex = regexp.MustCompile(`(?i)^\s*autonumber\s*$`)// fragmentStartRegex matches the opening line of a control-flow fragment, // e.g. "loop every minute", "opt is premium", "alt is valid". Group 1 is the // keyword, group 2 is the (optional) label describing the condition. fragmentStartRegex = regexp.MustCompile(`(?i)^\s*(loop|opt|alt|par|critical|break|rect)\b\s*(.*)$`)// fragmentDividerRegex matches a section divider inside a fragment: "else" // (alt), "and" (par), or "option" (critical). Group 1 is the keyword, group 2 // the (optional) label for the following section. fragmentDividerRegex = regexp.MustCompile(`(?i)^\s*(else|and|option)\b\s*(.*)$`)// rectColorRegex strips a leading rgb()/rgba() colour argument from a rect's // label (ASCII can't render the fill; PR6 draws a plain frame). rectColorRegex = regexp.MustCompile(`(?i)^\s*rgba?\([^)]*\)\s*`)// fragmentEndRegex matches the "end" line that closes a fragment. fragmentEndRegex = regexp.MustCompile(`(?i)^\s*end\s*$`)// boxStartRegex matches a participant-group opener: `box [color] [title]`. // Like participant/actor (and mermaid itself), the keyword wins at line // start, so a participant named "box …" can only message via quoting. boxStartRegex = regexp.MustCompile(`(?i)^\s*box(?:\s+(.*))?$`)// boxColorFuncRegex matches a functional color prefix on a box line: // rgb(…), rgba(…), hsl(…), hsla(…) — the argument list may contain spaces. boxColorFuncRegex = regexp.MustCompile(`(?i)^(?:rgba?|hsla?)\s*\([^)]*\)`)// boxHexColorRegex matches a leading #hex color token. boxHexColorRegex = regexp.MustCompile(`^#[0-9a-fA-F]{3,8}\b`)// activationRegex matches the standalone activation keywords: // `activate A` / `deactivate A`. Group 1 is the keyword, group 2 the name. activationRegex = regexp.MustCompile(`(?i)^\s*(activate|deactivate)\s+(.+)$`)// createRegex matches `create participant X` / `create actor X as Y`: the // participant appears at the message that follows. createRegex = regexp.MustCompile(`(?i)^\s*create\s+(participant|actor)\s+(.+)$`)// destroyRegex matches `destroy X`: X's lifeline ends at the message that // follows. destroyRegex = regexp.MustCompile(`(?i)^\s*destroy\s+(.+)$`)// brTagRegex matches <br> variants, which mermaid treats as line breaks; // single-line ASCII titles render them as spaces. brTagRegex = regexp.MustCompile(`(?i)<br\s*/?>`)// noteRegex matches note annotations: "Note over A: text", "note left of A: // text", "Note over A,B: text" (case-insensitive keyword). Group 1 is the // placement, group 2 the participant list, group 3 the text. noteRegex = regexp.MustCompile(`(?i)^\s*note\s+(right of|left of|over)\s+([^:]+?)\s*:\s*(.*)$`))// SequenceDiagram represents a parsed sequence diagram.typeSequenceDiagramstruct { Participants []*Participant// Messages is the flat list of every message arrow, in source order and // independent of any fragment nesting. Kept for callers that only care // about the messages themselves (and for backward compatibility). Messages []*Message// Events is the ordered body of the diagram used for rendering: each entry // is either a message or a fragment boundary. Walking Events reproduces the // original source order, including where loop/opt blocks open and close. Events []Event Autonumber bool// Boxes are participant groups declared with `box [color] [title] … end`; // each wraps a contiguous run of participants (they are declared inside // the block, so contiguity is inherent). Boxes []*Box// Created lists participants introduced by a `create` statement, whose // lifelines begin partway down the diagram rather than at the top. Created []*Participant}// Box is a participant group drawn as a frame around its participants'// columns. mermaid fills it with a color; ASCII draws a plain frame, so the// color is parsed (to keep it out of the title) and discarded.typeBoxstruct { Title string First, Last int// participant Index range, inclusive}// FragmentType identifies a control-flow fragment (a "framed" block of// messages) such as a loop or an optional section.typeFragmentTypeintconst (FragmentLoopFragmentType = iota// loop ... endFragmentOpt// opt ... endFragmentAlt// alt ... else ... endFragmentPar// par ... and ... endFragmentCritical// critical ... option ... endFragmentBreak// break ... endFragmentRect// rect ... end)func ( FragmentType) () string {switch {caseFragmentLoop:return"loop"caseFragmentOpt:return"opt"caseFragmentAlt:return"alt"caseFragmentPar:return"par"caseFragmentCritical:return"critical"caseFragmentBreak:return"break"caseFragmentRect:return"rect"default:returnfmt.Sprintf("FragmentType(%d)", int()) }}// fragmentKeywords maps an opener keyword to its fragment type.var fragmentKeywords = map[string]FragmentType{"loop": FragmentLoop, "opt": FragmentOpt, "alt": FragmentAlt,"par": FragmentPar, "critical": FragmentCritical,"break": FragmentBreak, "rect": FragmentRect,}// dividerKeywords maps a section-divider keyword to the fragment type it must// appear inside.var dividerKeywords = map[string]FragmentType{"else": FragmentAlt, "and": FragmentPar, "option": FragmentCritical,}// Fragment describes the opening of a control-flow block: its kind and the// optional condition text shown in the frame's label tab.typeFragmentstruct { Type FragmentType Label string}// EventKind tags each Event in the diagram body.typeEventKindintconst (EventMessageEventKind = iota// a message arrowEventFragmentStart// the opening line of a loop/opt/alt blockEventFragmentDivider// an "else" section divider within an altEventFragmentEnd// the matching "end" lineEventNote// a note annotationEventActivate// a participant becomes activeEventDeactivate// a participant stops being activeEventCreate// a participant's lifeline begins hereEventDestroy// a participant's lifeline ends here)func ( EventKind) () string {switch {caseEventMessage:return"message"caseEventFragmentStart:return"fragment-start"caseEventFragmentDivider:return"fragment-divider"caseEventFragmentEnd:return"fragment-end"caseEventNote:return"note"caseEventActivate:return"activate"caseEventDeactivate:return"deactivate"caseEventCreate:return"create"caseEventDestroy:return"destroy"default:returnfmt.Sprintf("EventKind(%d)", int()) }}// Event is one item in the diagram body. Exactly one payload field is set:// Message when Kind is EventMessage, Fragment when Kind is EventFragmentStart,// Note when Kind is EventNote. An EventFragmentEnd carries no payload; it just// marks where a block closes.typeEventstruct { Kind EventKind Message *Message Fragment *Fragment Note *Note// Participant is set for EventActivate / EventDeactivate: the lifeline // whose activation period starts or ends here. Participant *Participant}// NotePlacement describes where a note box sits relative to its participant(s).typeNotePlacementintconst (NoteOverNotePlacement = iota// note over A / note over A,BNoteLeftOf// note left of ANoteRightOf// note right of A)// Note is an annotation box drawn over or beside participant lifelines.typeNotestruct { Placement NotePlacement Participants []*Participant// one participant, or two for "over A,B" Text string}typeParticipantstruct { ID string Label string Index int// declared is true once a participant/actor statement names this // participant, as opposed to it being created implicitly by a message. declared bool}typeMessagestruct { From *Participant To *Participant Label string ArrowType ArrowType// CentralFrom / CentralTo mark central connections (mermaid's "()" on // either side of the arrow): a circle drawn where the message meets that // participant's lifeline. CentralFrom bool CentralTo bool Number int// Message number when autonumber is enabled (0 means no number)}typeArrowTypeintconst (SolidArrowArrowType = iota// ->> solid line with an arrowheadDottedArrow// -->> dotted line with an arrowheadSolidOpen// -> solid line, no arrowheadDottedOpen// --> dotted line, no arrowheadSolidCross// -x solid line, cross head (lost/failed message)DottedCross// --x dotted line, cross headSolidPoint// -) solid line, open point head (async message)DottedPoint// --) dotted line, open point headBidirectionalSolid// <<->> solid line, arrowheads both endsBidirectionalDotted// <<-->> dotted line, arrowheads both ends)// isDotted reports whether the arrow is drawn with a dotted (rather than solid)// line.func ( ArrowType) () bool {switch {caseDottedArrow, DottedOpen, DottedCross, DottedPoint, BidirectionalDotted:returntrue }returnfalse}// isBidirectional reports whether the arrow carries a head at the source end// too (mermaid's <<->> and <<-->>).func ( ArrowType) () bool {return == BidirectionalSolid || == BidirectionalDotted}// head returns the glyph drawn where the arrow meets the target lifeline, and// false for the open forms (-> and -->), which are drawn as a plain line// touching the lifeline. rightward selects the direction the head points.func ( ArrowType) ( BoxChars, bool) (rune, bool) {switch {caseSolidArrow, DottedArrow, BidirectionalSolid, BidirectionalDotted:if {return .ArrowRight, true }return .ArrowLeft, truecaseSolidCross, DottedCross:return .CrossHead, truecaseSolidPoint, DottedPoint:if {return .PointRight, true }return .PointLeft, true }return0, false}func ( ArrowType) () string {switch {caseSolidArrow:return"solid"caseDottedArrow:return"dotted"caseSolidOpen:return"solid-open"caseDottedOpen:return"dotted-open"caseSolidCross:return"solid-cross"caseDottedCross:return"dotted-cross"caseSolidPoint:return"solid-point"caseDottedPoint:return"dotted-point"caseBidirectionalSolid:return"bidirectional-solid"caseBidirectionalDotted:return"bidirectional-dotted"default:returnfmt.Sprintf("ArrowType(%d)", int()) }}func ( string) bool { := strings.Split(, "\n")for , := range { := strings.TrimSpace()if == "" || strings.HasPrefix(, "%%") {continue }returnhasSequenceKeyword() }returnfalse}// hasSequenceKeyword reports whether a line is the sequenceDiagram declaration,// case-insensitively (mermaid's sequence grammar is case-insensitive). The// keyword must stand as a whole token — followed by whitespace or end of line —// so a node id like "sequenceDiagramFoo" in a flowchart isn't misrouted here.func hasSequenceKeyword( string) bool { := strings.ToLower(strings.TrimSpace()) := strings.ToLower(SequenceDiagramKeyword)if !strings.HasPrefix(, ) {returnfalse } := [len():]return == "" || [0] == ' ' || [0] == '\t'}func ( string) (*SequenceDiagram, error) { = strings.TrimSpace()if == "" {returnnil, fmt.Errorf("empty input") } := diagram.SplitLines() := diagram.RemoveComments()iflen() == 0 {returnnil, fmt.Errorf("no content found") }if !hasSequenceKeyword(strings.TrimSpace([0])) {returnnil, fmt.Errorf("expected %q keyword", SequenceDiagramKeyword) } = [1:] := &SequenceDiagram{Participants: []*Participant{},Messages: []*Message{},Autonumber: false, } := make(map[string]*Participant)// openFragments is a stack of the fragment types currently open, so we can // reject an "end"/"else" with no matching opener, validate that "else" only // appears inside an "alt", and detect an opener with no matching "end".var []FragmentType// openBox is the box block currently being declared, if any. mermaid's // grammar allows only participant declarations inside a box, and boxes // cannot nest.var *Box// active counts each participant's open activation periods, so deactivating // an inactive participant is an error and stacked activations balance. := map[*Participant]int{}// pendingCreate / pendingDestroy hold a participant named by a `create` or // `destroy` statement. mermaid attaches each to the message that follows, // which must involve that participant.var , *Participantvar , intfor , := range { := strings.TrimSpace()if == "" {continue }// Inside a box block only participant/actor declarations (and the // closing "end") are valid, so handle that mode first.if != nil {iffragmentEndRegex.MatchString() { = nilcontinue }ifboxStartRegex.MatchString() {returnnil, fmt.Errorf("line %d: boxes cannot nest", +2) } , , := .parseParticipant(, )if != nil {returnnil, fmt.Errorf("line %d: %w", +2, ) }if ! {returnnil, fmt.Errorf("line %d: only participant declarations are allowed inside a box: %q", +2, ) }if .First == -1 { .First = .Index } .Last = .Indexcontinue }// Check for autonumber directiveifautonumberRegex.MatchString() { .Autonumber = truecontinue }// A box opener starts a participant group; its optional color is // parsed away (no ASCII meaning) so it never leaks into the title.if := boxStartRegex.FindStringSubmatch(); != nil { = &Box{Title: parseBoxTitle([1]), First: -1} .Boxes = append(.Boxes, )continue }// Notes carry no arrow, so they never collide with messages; a // placement keyword is required, so a participant named "Note" (e.g. // "Note->>B: hi") still parses as a message further down.if := noteRegex.FindStringSubmatch(); != nil { := NoteOverswitchstrings.ToLower([1]) { // keyword may be any casecase"left of": = NoteLeftOfcase"right of": = NoteRightOf }var []*Participantfor , := rangestrings.Split([2], ",") { = strings.Trim(strings.TrimSpace(), `"`)if != "" { = append(, .getParticipant(, )) } }iflen() == 0 {returnnil, fmt.Errorf("line %d: note without a participant", +2) }// Mermaid allows an optional wrap:/nowrap: prefix on note text; // wrapping is irrelevant for single-line ASCII, so just strip it. := strings.TrimSpace([3])for , := range []string{"nowrap:", "wrap:"} {ifstrings.HasPrefix(strings.ToLower(), ) { = strings.TrimSpace([len():])break } } .Events = append(.Events, Event{Kind: EventNote,Note: &Note{Placement: , Participants: , Text: }, })continue }if , , := .parseParticipant(, ); != nil {returnnil, fmt.Errorf("line %d: %w", +2, ) } elseif {continue }// Messages are checked before fragment keywords so a participant named // "loop"/"opt"/"end" (e.g. "loop->>B: hi") is still read as a message — // only bare openers like "loop retry" fall through to the checks below. := len(.Events)if , := .parseMessageEvent(, , ); != nil {returnnil, fmt.Errorf("line %d: %w", +2, ) } elseif {// A create/destroy statement binds to this, the next message, which // must involve its participant: mermaid requires a created // participant to be the recipient (it cannot send the message that // brings it into being) and a destroyed one to be at either end. := .Events[].Messageif := ; != nil { = nilif .To != {returnnil, fmt.Errorf("line %d: the created participant %q must receive the message that creates it", , .ID) }// The lifeline starts at this message, so the event precedes it. .Events = append(.Events, Event{})copy(.Events[+1:], .Events[:]) .Events[] = Event{Kind: EventCreate, Participant: } }if := ; != nil { = nilif .From != && .To != {returnnil, fmt.Errorf("line %d: the destroyed participant %q is not involved in the following message", , .ID) }// The lifeline ends after this message. .Events = append(.Events, Event{Kind: EventDestroy, Participant: }) }continue }// `create participant X` / `create actor X as Y`: declare X, then bind // it to the message that follows.if := createRegex.FindStringSubmatch(); != nil {// mermaid rejects creating an id that already exists, even one only // implied by an earlier message, and points at AS aliases instead.if , := parseName(nameBeforeAlias([2])); && [] != nil {returnnil, fmt.Errorf("line %d: cannot create participant %q: the id already exists, use an \"as\" alias for a distinct participant", +2, ) } , := .declareParticipant([2], )if != nil {returnnil, fmt.Errorf("line %d: %w", +2, ) } , = , +2 .Created = append(.Created, )continue }// `destroy X`: end X's lifeline at the message that follows.if := destroyRegex.FindStringSubmatch(); != nil { , := parseName([1])if ! {returnnil, fmt.Errorf("line %d: invalid participant name %q", +2, [1]) } , := []if ! {returnnil, fmt.Errorf("line %d: cannot destroy unknown participant %q", +2, ) } , = , +2continue }// Standalone activation keywords. Checked after messages so a // participant named "activate …" can still send one.if := activationRegex.FindStringSubmatch(); != nil { , := parseName([2])if ! {returnnil, fmt.Errorf("line %d: invalid participant name %q", +2, [2]) } := .getParticipant(, )ifstrings.EqualFold([1], "activate") { []++ .Events = append(.Events, Event{Kind: EventActivate, Participant: }) } else {if [] == 0 {returnnil, fmt.Errorf("line %d: trying to deactivate an inactive participant %q", +2, .ID) } []-- .Events = append(.Events, Event{Kind: EventDeactivate, Participant: }) }continue }// A fragment opener (loop/opt/alt/par/critical/break/rect) starts a block.if := fragmentStartRegex.FindStringSubmatch(); != nil { := fragmentKeywords[strings.ToLower([1])] := strings.TrimSpace([2])// rect's argument is a fill colour we can't render in ASCII; drop it // so the frame is drawn plain (colour support is a follow-up).if == FragmentRect { = strings.TrimSpace(rectColorRegex.ReplaceAllString(, "")) } .Events = append(.Events, Event{Kind: EventFragmentStart,Fragment: &Fragment{Type: , Label: }, }) = append(, )continue }// A section divider: "else" (alt), "and" (par), "option" (critical). It // must sit directly inside the matching fragment type.if := fragmentDividerRegex.FindStringSubmatch(); != nil { := dividerKeywords[strings.ToLower([1])]iflen() == 0 || [len()-1] != {returnnil, fmt.Errorf("line %d: %q outside a matching %s block", +2, , ) } .Events = append(.Events, Event{Kind: EventFragmentDivider,Fragment: &Fragment{Type: , Label: strings.TrimSpace([2])}, })continue }// "end" closes the most recently opened fragment.iffragmentEndRegex.MatchString() {iflen() == 0 {returnnil, fmt.Errorf("line %d: %q without a matching fragment opener", +2, ) } .Events = append(.Events, Event{Kind: EventFragmentEnd}) = [:len()-1]continue }returnnil, fmt.Errorf("line %d: invalid syntax: %q", +2, ) }if := ; != nil {returnnil, fmt.Errorf("line %d: the created participant %q must be followed by a message involving it", , .ID) }if := ; != nil {returnnil, fmt.Errorf("line %d: the destroyed participant %q must be followed by a message involving it", , .ID) }if != nil {returnnil, fmt.Errorf("unclosed box: missing \"end\"") }iflen() > 0 {returnnil, fmt.Errorf("unclosed fragment: missing %d \"end\"", len()) }iflen(.Participants) == 0 {returnnil, fmt.Errorf("no participants found") }// A box declared with no participants has nothing to frame; drop it. := .Boxes[:0]for , := range .Boxes {if .First >= 0 { = append(, ) } } .Boxes = return , nil}// parseParticipant handles a participant/actor declaration. It reports whether// the line was one, and returns the participant it created or claimed so a// caller (the box block) can record which lifeline was declared.func ( *SequenceDiagram) ( string, map[string]*Participant) (*Participant, bool, error) { := participantRegex.FindStringSubmatch()if == nil {returnnil, false, nil } , := .declareParticipant([1], )return , true, }// nameBeforeAlias returns the id portion of an "ID [as Label]" declaration.func nameBeforeAlias( string) string { = strings.TrimSpace()if := participantAsRegex.FindStringSubmatch(); != nil {return [1] }return}// declareParticipant records a participant from the "[ID] [as Label]" part of a// declaration, shared by participant/actor statements and by `create`.func ( *SequenceDiagram) ( string, map[string]*Participant) (*Participant, error) { = strings.TrimSpace() := := ""if := participantAsRegex.FindStringSubmatch(); != nil { , = [1], [2] } , := parseName()if ! {returnnil, fmt.Errorf("invalid participant name %q", ) }if == "" { = } = strings.Trim(, `"`)// A participant already created implicitly by an earlier message may be // declared afterwards to give it a label or put it in a box, as mermaid // allows (addActor updates an existing actor). Only declaring the same // participant twice is an error.if , := []; {if .declared {returnnil, fmt.Errorf("duplicate participant %q", ) } .declared = true .Label = return , nil } := &Participant{ID: ,Label: ,Index: len(.Participants),declared: true, } .Participants = append(.Participants, ) [] = return , nil}// parseBoxTitle extracts the display title from a box opener's argument:// an optional leading color (functional rgb()/hsl(), #hex, or a CSS color// name — mermaid fills the box with it, ASCII has no use for it) followed by// the title text. <br> tags become spaces, as elsewhere in single-line ASCII.func parseBoxTitle( string) string { = strings.TrimSpace(brTagRegex.ReplaceAllString(, " "))if := boxColorFuncRegex.FindStringIndex(); != nil {returnstrings.TrimSpace([[1]:]) }if := boxHexColorRegex.FindStringIndex(); != nil {returnstrings.TrimSpace([[1]:]) } := if := strings.IndexAny(, " \t"); >= 0 { = [:] }ifcssColorNames[strings.ToLower()] {returnstrings.TrimSpace([len():]) }return}// cssColorNames is the set of CSS color keywords (plus "transparent") that// mermaid accepts as a box fill. Needed to split "box Green New serwis"// (color Green, title "New serwis") from "box Facade" (no color, title// "Facade") the way mermaid does.var cssColorNames = func() map[string]bool {const = "aliceblue antiquewhite aqua aquamarine azure beige bisque black blanchedalmond blue " +"blueviolet brown burlywood cadetblue chartreuse chocolate coral cornflowerblue cornsilk crimson " +"cyan darkblue darkcyan darkgoldenrod darkgray darkgreen darkgrey darkkhaki darkmagenta " +"darkolivegreen darkorange darkorchid darkred darksalmon darkseagreen darkslateblue darkslategray " +"darkslategrey darkturquoise darkviolet deeppink deepskyblue dimgray dimgrey dodgerblue firebrick " +"floralwhite forestgreen fuchsia gainsboro ghostwhite gold goldenrod gray green greenyellow grey " +"honeydew hotpink indianred indigo ivory khaki lavender lavenderblush lawngreen lemonchiffon " +"lightblue lightcoral lightcyan lightgoldenrodyellow lightgray lightgreen lightgrey lightpink " +"lightsalmon lightseagreen lightskyblue lightslategray lightslategrey lightsteelblue lightyellow " +"lime limegreen linen magenta maroon mediumaquamarine mediumblue mediumorchid mediumpurple " +"mediumseagreen mediumslateblue mediumspringgreen mediumturquoise mediumvioletred midnightblue " +"mintcream mistyrose moccasin navajowhite navy oldlace olive olivedrab orange orangered orchid " +"palegoldenrod palegreen paleturquoise palevioletred papayawhip peachpuff peru pink plum " +"powderblue purple rebeccapurple red rosybrown royalblue saddlebrown salmon sandybrown seagreen " +"seashell sienna silver skyblue slateblue slategray slategrey snow springgreen steelblue tan teal " +"thistle tomato turquoise violet wheat white whitesmoke yellow yellowgreen transparent" := map[string]bool{}for , := rangestrings.Fields() { [] = true }return}()// findArrow returns the index and token of the first arrow in line, skipping// quoted spans. This mirrors mermaid's lexer, where a name may contain '-'// (Alice-in-Wonderland) or spaces (cron job) because only a '-' or '<' that// starts a real arrow token can end it.func findArrow( string) (int, string) { := falsefor := 0; < len(); ++ {switch {case [] == '"': = !case ! && ([] == '-' || [] == '<'):for , := rangearrowTokens {ifstrings.HasPrefix([:], ) {return , } } } }return -1, ""}// validName reports whether an unquoted participant name is acceptable.// Mermaid's ACTOR token excludes these characters; anything else (spaces,// dashes not forming an arrow, '=', '.', ...) is a legal name.func validName( string) bool {return != "" && !strings.ContainsAny(, `"<>:,;(`)}// parseName extracts a participant name: either a quoted string or a bare// name validated by validName.func parseName( string) (string, bool) { = strings.TrimSpace()iflen() >= 2 && strings.HasPrefix(, `"`) && strings.HasSuffix(, `"`) { := [1 : len()-1]return , != "" && !strings.Contains(, `"`) }return , validName()}// splitMessage breaks a line into [From][()][arrow][()][To]: [Label], where// "()" marks a central connection on that side. ok is false when the line is// not a message, so parsing can fall through to the other statement forms.func splitMessage( string) ( messageParts, bool) { , := findArrow()if < 0 {return } .arrow = := strings.TrimSpace([:])// A line opening with a fragment keyword is a fragment statement whose // label happens to contain an arrow, never a message. Quoted names are // exempt: `"loop svc" ->> B` is an explicit participant reference.if !strings.HasPrefix(, `"`) && fragmentKeywordRegex.MatchString() {return }ifstrings.HasSuffix(, "()") { .centralFrom = true = strings.TrimSpace(strings.TrimSuffix(, "()")) } , := parseName() .fromID = // A '+' or '-' after the arrow is the activation shorthand: '+' activates // the receiver, '-' deactivates the sender. mermaid's lexer skips // whitespace and no name may begin with a sign, so the sign is recognised // either side of a space. := strings.TrimLeft([+len():], " \t")if != "" && ([0] == '+' || [0] == '-') { .activateTo = [0] == '+' .deactivateFrom = [0] == '-' = [1:] } = strings.TrimSpace()ifstrings.HasPrefix(, "()") { .centralTo = true = strings.TrimSpace(strings.TrimPrefix(, "()")) }// The label starts at the first ':' after the (possibly quoted) to-name. := 0ifstrings.HasPrefix(, `"`) {if := strings.Index([1:], `"`); >= 0 { = + 2 } } := strings.Index([:], ":")if < 0 {return } += , := parseName([:]) .toID = .label = strings.TrimSpace([+1:]) = && return}// messageParts is the decomposition of a message line: endpoints, arrow, label,// central-connection markers and the activation shorthand suffix.type messageParts struct { fromID, arrow, toID, label string centralFrom, centralTo bool activateTo bool// "+" after the arrow: activate the receiver deactivateFrom bool// "-" after the arrow: deactivate the sender}func ( *SequenceDiagram) ( string, map[string]*Participant, map[*Participant]int) (bool, error) { , := splitMessage()if ! {returnfalse, nil } := .getParticipant(.fromID, ) := .getParticipant(.toID, )varArrowTypeswitch .arrow {case"->>": = SolidArrowcase"-->>": = DottedArrowcase"->": = SolidOpencase"-->": = DottedOpencase"-x": = SolidCrosscase"--x": = DottedCrosscase"-)": = SolidPointcase"--)": = DottedPointcase"<<->>": = BidirectionalSolidcase"<<-->>": = BidirectionalDotted } := 0if .Autonumber { = len(.Messages) + 1 } := &Message{From: ,To: ,Label: .label,ArrowType: ,CentralFrom: .centralFrom,CentralTo: .centralTo,Number: , } .Messages = append(.Messages, ) .Events = append(.Events, Event{Kind: EventMessage, Message: })// Activation shorthand: the period starts (or ends) after the message that // carries the suffix, so the arrow itself sits on the boundary.if .activateTo { []++ .Events = append(.Events, Event{Kind: EventActivate, Participant: }) }if .deactivateFrom {if [] == 0 {returntrue, fmt.Errorf("trying to deactivate an inactive participant %q", .ID) } []-- .Events = append(.Events, Event{Kind: EventDeactivate, Participant: }) }returntrue, nil}func ( *SequenceDiagram) ( string, map[string]*Participant) *Participant {if , := []; {return } := &Participant{ID: ,Label: ,Index: len(.Participants), } .Participants = append(.Participants, ) [] = return}
The pages are generated with Goldsv0.8.7. (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu.
PR and bug reports are welcome and can be submitted to the issue list.
Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds.